using System.Reflection;
using BLL.Manager;
using DAL;
using HZY.Framework.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Model.Entity;
using NLog.Extensions.Logging;
using SqlSugar;
using LogManager = NLog.LogManager;

namespace WinFormsSprayProcessSCADASystem
{
    internal static class Program
    {
        private static IWebHost _webHost;
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //注册服务容器
            var services = new ServiceCollection();

            ConfigureServicer(services);

            ServiceProvider serviceProvider = services.BuildServiceProvider();
            Globals.ServiceProvider = serviceProvider;
            Globals.Logger = serviceProvider.GetRequiredService<BLL.Manager.LogManager>();

            ApplicationConfiguration.Initialize();

            FormLogin loginFrom = serviceProvider.GetRequiredService<FormLogin>();

            var db = serviceProvider.GetRequiredService<ISqlSugarClient>();
#if DEBUG
            try
            {
                db.CodeFirst.SetStringDefaultLength(200)
            .InitTables(typeof(AuthEntity), typeof(DataLogEntity), typeof(RecipeEntity), typeof(UserEntity), typeof(RoleEntity), typeof(RouteEntity), typeof(RouteBtRoleEntity), typeof(LogEntity));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }
#endif

            //初始化web服务
            //InitWebService();

            Application.Run(loginFrom);

            // 注册应用程序退出事件
            Application.ApplicationExit += (sender, e) =>
            {
                _webHost?.Dispose();
                db.Dispose();
            };
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = e.ExceptionObject as Exception;
            Console.WriteLine(exception.Message);
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Exception exception = e.Exception;
            Console.WriteLine(exception.Message);
        }

        private static void ConfigureServicer(ServiceCollection services)
        {
            services.AddDependencyInjection(options =>
            {
                options.Assemblies = new List<Assembly>()
                {
                    typeof(Program).Assembly,
                    typeof(UserManager).Assembly,
                    typeof(DB).Assembly
                };
            });

            //注册json配置
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");

            //构建json配置
            IConfigurationRoot configuration = configurationBuilder.Build();

            //注入json单例对象
            services.AddSingleton<IConfiguration>(configuration).AddLogging(loggerBuilder =>
            {
                loggerBuilder.ClearProviders();
                loggerBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                loggerBuilder.AddNLog();
            });

            //获取nlog配置
            var nlogConfig = configuration.GetSection("NLog");

            //nlog设置配置
            LogManager.Configuration = new NLogLoggingConfiguration(nlogConfig);

            //注入SQlSugar单例对象
            DbType type = Enum.Parse<DbType>(Globals.IniFile.ReadString("DB", "type", "MySql"));
            string connectStr = Globals.IniFile.ReadString("DB", "database", "server=localhost;Database=db_scada;Uid=root;Pwd=Aa123456");
            services.AddSqlSugarSetup(type, connectStr);
        }

        private static void InitWebService()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string staticFilesPath = Path.Combine(baseDirectory, "WWWRoot/dist");
            Console.WriteLine(staticFilesPath);
            _webHost = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    options.ListenAnyIP(25378);
                })
                .ConfigureServices(services =>
                {
                    services.AddSpaStaticFiles(configuration =>
                    {
                        configuration.RootPath = staticFilesPath;
                    });
                })
                .Configure(app =>
                {
                    // 配置静态文件
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(staticFilesPath),
                        RequestPath = ""
                    });

                    // 处理SPA路由
                    app.MapWhen(ctx => !ctx.Request.Path.Value.StartsWith("/api/") &&
                                       !Path.HasExtension(ctx.Request.Path.Value),
                        client =>
                        {
                            client.Run(async context =>
                            {
                                context.Response.ContentType = "text/html";
                                await context.Response.SendFileAsync(Path.Combine(staticFilesPath, "index.html"));
                            });
                        });
                })
            .Build();

            _webHost.Start(); // 启动服务器
        }
    }
}